package com.flux.tms.tm${bean.numMain}web.modules.t${bean.numMain}${bean.numSub};

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.flux.tms.tm${bean.numMain}web.modules.t${bean.numMain}${bean.numSub}.service.${(bean.detailTableList)[i].javaFlieName}WebService;
import com.flux.scev6.appsecret.AppSecretService;
import com.flux.scev6.constant.CommonCVal;
import com.flux.scev6.dbopr.BaseDao;
import com.flux.scev6.dbopr.QueryHelper;
import com.flux.scev6.dbopr.dbhelper.DbHelper;
import com.flux.scev6.dbopr.model.ResultObj;
import com.flux.scev6.dbopr.query.pagequery.PageQueryDataSet;
import com.flux.scev6.function.functionhelper.BizHelper;
import com.flux.scev6.function.functionhelper.SFHelper;
import com.flux.scev6.importbiz.ImpFmFileCVal;
import com.flux.scev6.importbiz.impfmcsv.ImportFromCsvUtil;
import com.flux.scev6.importbiz.impfmexcel.ImportFromExcelUtil;
import com.flux.scev6.language.multilang.MultiLangHandler;
import com.flux.scev6.login.LoginInfoUtil;
import com.flux.scev6.login.model.LoginInfoObj;
import com.flux.scev6.privilege.ActionPrivCheckService;
import com.flux.scev6.rpc.hessian.api.IHessianClient;
import com.flux.scev6.rpc.rpc.RemoteServiceUtil;
import com.flux.scev6.udfquery.model.QrySqlObj;
import com.flux.scev6.utils.BizDataUtil;
import com.flux.scev6.utils.ResultObjUtil;
import com.flux.scev6.utils.datetime.DateFormatUtil;
import com.flux.scev6.utils.web.QueryStringUtil;
import com.flux.scev6.webservice.api.IJsonResult;
import com.flux.scev6.webservice.api.IWebLoginInfo;
import com.flux.scev6.webservice.impl.DefaultJsonResult;
import com.flux.scev6.webservice.impl.DefaultJsonWebService;
import org.springframework.stereotype.Component;
/**
*
* T${bean.numMain}${bean.numSub} ${bean.notesMain} -- ${detail.subFunctionName}   -- web 控制层实现
*
* T${bean.numMain}${bean.numSub} ${detail.subFunctionName}
*
* <p>
* 创建时间：${bean.dayTime}
* <p>
*
* <p>
* 修改时间：${bean.dayTime}
* <p>
*
* @author ${bean.author}
*
* @version V1.0.0
*
*/
@Component("t${bean.numMain}${bean.numSub}_${((bean.detailTableList)[i]).subTableName}")
public class ${((bean.detailTableList)[i]).javaFlieName} extends DefaultJsonWebService{
    /**
     * V100(${bean.numTime}) ${bean.author} 初版。 
     */
    @SuppressWarnings("unused")
    private static String verNum = "V100(${bean.numTime})";// 版本号
    @Autowired
    private AppSecretService appSecretService;
    @Autowired
    private IHessianClient hessianClient;
    @Autowired
    private RemoteServiceUtil remoteServiceUtil;
    @Autowired
    private ActionPrivCheckService actionPrivCheckService;
    


    /**
     *  查询 ${detail.subFunctionName}信息
     * 
     * <p>Author: ${bean.author}
     * <p>Create Time: ${bean.dayTime}
     * 
     * @param request
     * @param response
     * @param webLoginInfo
     * @return
     * @throws IOException
     * @throws ServletException
     */
    public IJsonResult getDetailsList(HttpServletRequest request, HttpServletResponse response,
            IWebLoginInfo webLoginInfo) throws IOException, ServletException {
     
        // ============================================================================
        // ============================================================================
        DefaultJsonResult result = new DefaultJsonResult();
        // 获取登录信息对象
        LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${detail.javaFlieName}CVal.FUNC_ID);
        // 根据当前登录信息对象构造多语言处理器
        MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);
        // ============================================================================
        try { 
            String[] actionIds =${detail.javaFlieName}CVal.PRIVID_QRY;
            boolean hasPrivilege = actionPrivCheckService.check(loginInfoObj,${detail.javaFlieName}CVal.FUNC_ID, actionIds);
            if (!hasPrivilege) {
                // 没有对应的操作权限
                String msg = mlh.getText(CommonCVal.ERRID_009);
                result.setErrMsg(msg);
                result.setOK(false);    
                return result;
            }
            // 获取用户输入的查询条件
            Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);
            //获取其他需要返回的字段
            String otherReturnFields = getOtherRFs(loginInfoObj).toString();
            // 执行分页查询
            PageQueryDataSet pageQueryDataSet = ${detail.javaFlieName}Service.get${detail.javaFlieName}sListByPage(loginInfoObj,
                    conditionMap, otherReturnFields);
            if ("OK".equalsIgnoreCase(pageQueryDataSet.getResult())) {
                // 执行成功
                result.setBizJson(pageQueryDataSet.getBizData());// 业务数据
                result.setPageQueryInfo(pageQueryDataSet.getPageInfo()); // 分页信息
                result.setErrMsg(pageQueryDataSet.getMsg());
                result.setOK(true);
            } else {
                // 执行失败
                String msg = mlh.getText(pageQueryDataSet.getMsg(), new Object[] { CommonCVal.ERRID_W102 });
                result.setErrMsg(msg);
                result.setOK(false);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });
            result.setErrMsg(msg);
            result.setOK(false);
        }
        return result;
        // ============================================================================
        // ============================================================================
        
    }
    
    /**
     * 其他返回字段
     * 
     * <p>Author: ${bean.author}
     * <p>Create Time: ${bean.dayTime}
     * 
     * @param loginInfoObj
     * @return
     */
    private StringBuffer getOtherRFs(LoginInfoObj loginInfoObj) {
        // 获取不同类型数据库对应的helper
        DbHelper dbHelper = ${detail.javaFlieName}Service.getDao().getDbHelper();
        String pattern = DateFormatUtil.getDateFormat(loginInfoObj); // 精确到天
        String pattern2 = DateFormatUtil.getFormat(loginInfoObj); // 精确到时分秒
        StringBuffer otherRFs = new StringBuffer(100);
        <#list (detail.tableList)! as tableId>
            <#if (tableId)?contains("birthday")||(tableId)?contains("date")||(tableId)?contains("Date")||(tableId)?contains("Birthday")||(tableId)?contains("time")||(tableId)?contains("Time")>
        otherRFs.append(dbHelper.to_char("h1.${tableId}", pattern2)).append(" AS ${tableId}, ");
            <#else>
        otherRFs.append("h1.${tableId},");
            </#if>
        </#list>
        // udf
        otherRFs.append("h1.udf01,h1.udf02,h1.udf03,h1.udf04,h1.udf05,");
        otherRFs.append("h1.oprSeqFlag,");
        otherRFs.append("h1.addWho,");
        otherRFs.append("h1.noteText,");
        otherRFs.append("h1.currentVersion,");
        otherRFs.append("h1.editWho,");
        otherRFs.append(dbHelper.to_char("h1.addTime", pattern2)).append(" AS addTime, ");
        otherRFs.append(dbHelper.to_char("h1.editTime", pattern2)).append(" AS editTime ");
        return otherRFs;
    }
   /**
    *  员工 详情 管理(新增、复制、编辑、删除)
    *
    * @author: ${bean.author}
    * @date: ${bean.dayTime}
    * @param request
    * @param response
    * @param webLoginInfo
    * @return
    * @throws IOException
    * @throws ServletException
    */
    public IJsonResult saveDetailData(HttpServletRequest request, HttpServletResponse response,
            IWebLoginInfo webLoginInfo) throws IOException, ServletException {
        // ============================================================================
        // ============================================================================
        DefaultJsonResult result = new DefaultJsonResult();
        String   functionId  = ${detail.javaFlieName}CVal.FUNC_ID;
        // 获取登录信息对象
        LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${detail.javaFlieName}CVal.FUNC_ID);
        // 根据当前登录信息对象构造多语言处理器
        MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);
        try {
            // 获取用户输入的数据
            Map<String, String> bizdataMap = QueryStringUtil.getQueryStringMap(request);
            // 检查操作标记
            boolean isContinue = false;
            String oprFlag = bizdataMap.get(CommonCVal.OPRFLAG);
            if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag) || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)
                    || CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)
                    || CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
                // =========================================================================
                isContinue = true;
            }
            if (!isContinue) {
                // 不支持的操作标记
                result.setErrMsg("EX91: not supported oprFlag");
                result.setOK(false);
                return result;
            }
            //增加操作权限检查
            String[] actionIds = null;      
            if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag) 
                    || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)) {
                // 新增、复制
                actionIds = ${detail.javaFlieName}CVal.PRIVID_DETAIL_ADD;
            } else if (CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
                // 编辑
                actionIds = ${detail.javaFlieName}CVal.PRIVID_DETAIL_EDT;
            } else if (CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
                // 删除
                actionIds = ${detail.javaFlieName}CVal.PRIVID_DETAIL_DEL;
            }
            boolean hasPrivilege = actionPrivCheckService.check(loginInfoObj, functionId, actionIds);
            if (!hasPrivilege) {
                // 没有对应的操作权限
                String msg = mlh.getText(CommonCVal.ERRID_009);
                result.setErrMsg(msg);
                result.setOK(false);    
                return result;
            }
            // 组织输入参数，调用服务类准备

            // 当前用户登录的企业组织编号 // 注意：极其重要！
            bizdataMap.put(${detail.javaFlieName}CVal.KEYNAME_ORGANIZATIONID, loginInfoObj.getBizOrgId());
            String appSecret = appSecretService.getAppSecret();
            String loginInfo = LoginInfoUtil.toJSONString(loginInfoObj, appSecret);
            String bizData = BizDataUtil.toJSONString(bizdataMap, appSecret);
            String srvResult = null;
            // ==============================================================================
            // ==============================================================================
            if (remoteServiceUtil.isHessian()) {
                // 通过Hessian方式调用后端服务类程序
                String clsId = "${detail.javaFlieName}ServiceProvider";//这里的clsId必须和Srv端的Hessian配置里面的id相同否则会找不到服务类
                String method = null;
                String version = "1.0.0";
                if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag)
                        || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)) {
                    // 新增、复制
                    method = "add${detail.javaFlieName}";
                } else if (CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
                    // 编辑
                    method = "update${detail.javaFlieName}";
                } else if (CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
                    // 删除
                    method = "delete${detail.javaFlieName}";
                }
                srvResult = hessianClient.doAction(clsId, method, version, loginInfo, bizData);
            }
            //else if (bizStaffJobServiceProvider != null) {
                // 通过HSF方式调用后端服务类程序
                // 调用对应的后端服务类程序
               // if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag)
               //         || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)) {
                    // 新增、复制
              //      srvResult = ${detail.javaFlieName}ServiceProvider.add${detail.javaFlieName}(loginInfo, bizData);
              //  } else if (CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
                    // 编辑
              //      srvResult = ${detail.javaFlieName}ServiceProvider.update${detail.javaFlieName}(loginInfo, bizData);
             //   } else if (CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
                    // 删除
             //       srvResult = ${detail.javaFlieName}ServiceProvider.delete${detail.javaFlieName}(loginInfo, bizData);
             //   }
           // }
            // ==============================================================================
            // ==============================================================================
            // 处理服务类返回的结果信息
            ResultObj resultObj = ResultObjUtil.fromJSONString(srvResult, appSecret);
            if (resultObj.isCodeValueOK()) {
                // 服务类执行成功
                // 使用服务类返回的主键值完成后续的操作。
                Map<String, String> conditionMap = new HashMap<String, String>();
                conditionMap.put(${detail.javaFlieName}CVal.KEYNAME_ORGANIZATIONID, loginInfoObj.getBizOrgId());
                conditionMap.put(${detail.javaFlieName}CVal.KEYNAME_${(detail.pk02) ?upper_case}, resultObj.getPkey02());
<#if (detail.pk03)!="">
                conditionMap.put(${detail.javaFlieName}CVal.KEYNAME_${(detail.pk03) ?upper_case}, resultObj.getPkey03());</#if>
    <#if (detail.pk04)!="">
                conditionMap.put(${detail.javaFlieName}CVal.KEYNAME_${(detail.pk04) ?upper_case}, resultObj.getPkey04());</#if>
    //自定义查询配置
                conditionMap.put("queryName", bizdataMap.get("queryName"));
                // 查询最新的数据
                String bizJson = "[]";
                if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag)
                        || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)
                        || CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)
                        || CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
                    // 获取其他返回字段
                    String otherReturnFields = getOtherRFs(loginInfoObj).toString();
                    // 执行查询

                    PageQueryDataSet pageQueryDataSet = ${detail.javaFlieName}Service.get${detail.javaFlieName}sListByPage(loginInfoObj,
                    conditionMap, otherReturnFields);
                    SFHelper.processResultData_withOutPage(result, mlh, pageQueryDataSet);
                    List<Map<String, Object>> rsData = pageQueryDataSet.getBizDataList();
                    if(rsData!=null){
                        String rsDataStr = JSON.toJSONString(rsData);
                        result.setBizJson(rsDataStr);
                        result.setOK(true);
                    }else{
                        String rsData2 = pageQueryDataSet.getBizData();
                        result.setBizJson(rsData2);
                        result.setOK(true);
                    }
                }
                result.setBizJson(bizJson);
                result.setOK(true);
            } else {
                // 错误处理 //把消息Id翻译成当前用户使用语言对应的文本描述
                String tableName = ${detail.javaFlieName}CVal.T_BAS_STAFF;
                String msg = mlh.getServiceMessage(tableName, resultObj.getMessageId(), resultObj.getMessage());
                result.setErrMsg(msg);
                result.setOK(false);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的错误编号值待完善
            result.setErrMsg(msg);
            result.setOK(false);
        }
        return result;
        // ============================================================================
        // ============================================================================
    }
    
   /**
    * 获取查询配置信息,此方法在自定义配置的时候会使用到
    * 
    * <p>Author: ${bean.author}
    * <p>Create Time: ${bean.dayTime}
    * 
    * @param request
    * @param response
    * @param webLoginInfo
    * @return
    * @throws IOException
    * @throws ServletException
    */
    public IJsonResult getQryTableList(HttpServletRequest request, HttpServletResponse response,IWebLoginInfo webLoginInfo) throws IOException, ServletException {
        // ===============================================================================================================
        // ===============================================================================================================
        DefaultJsonResult result = new DefaultJsonResult();
        // 获取登录信息对象
        LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${detail.javaFlieName}CVal.FUNC_ID);
        // 根据当前登录信息对象构造多语言处理器
        MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);
        try {
            // 获取用户输入的查询条件
            Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);
            String otherReturnFields = getOtherRFs(loginInfoObj).toString();
            QrySqlObj qrySqlObj = new QrySqlObj();  // 表对象属性列表
            String queryName = "";
            // 获取查询列表名称
            if (conditionMap != null && conditionMap.size() > 0 && conditionMap.containsKey("queryName")) {
                queryName = conditionMap.get("queryName");
            }
            if (queryName.length() > 0) {
                qrySqlObj = ${detail.javaFlieName}Service.getQuerySql(loginInfoObj, conditionMap, otherReturnFields, false);
            }
            // 转JSON字符串返回
            if (qrySqlObj != null) {
                result.setBizJson(JSON.toJSONString(qrySqlObj));
            }
            result.setOK(true);
            
        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[]{ CommonCVal.ERRID_W100 });// 这里的 错误编号值 待完善
            result.setErrMsg(msg);
            result.setOK(false);
        }
        return result;
    }

    /**
    * 导入数据
    *
    * @author ${bean.author}
    *
    * @date ${bean.dayTime}
    *
    * @param request
    * @param response
    * @param webLoginInfo
    * @return
    * @throws IOException
    * @throws ServletException
    */
    public IJsonResult importData(HttpServletRequest request, HttpServletResponse response, IWebLoginInfo webLoginInfo)
    throws IOException, ServletException {


        //System.out.println("importData");
        // ============================================================================
        // ============================================================================
        // ============================================================================
        DefaultJsonResult result = new DefaultJsonResult();
        // 获取登录信息对象
        LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${detail.javaFlieName}CVal.FUNC_ID);
        // 根据当前登录信息对象构造多语言处理器
        MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);

        // 获取用户输入的查询条件
        Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);
        try {
        // 读写分离，设置数据源名称 -- V5WMS 写主库
        BaseDao.setDataSourceName(CommonCVal.DS_MASTERWRITE);

        String tableId = conditionMap.get("tableId");
        String fileType = conditionMap.get("fileType");
        String strMSGLTM = conditionMap.get("msgLtm");
        String currentSheetNo = conditionMap.get("sheetNo");
        String rowNoOfFieldName = conditionMap.get("fieldNo");
        String rowNoOfBeginDataRow = conditionMap.get("beginNo");
        String rowNoOfEndDataRow = conditionMap.get("endNo");
        String isContinueToNextRow = conditionMap.get("errorContinue");

    Imp${detail.javaFlieName}FmExcelHelper impHelper = new Imp${detail.javaFlieName}FmExcelHelper(request, loginInfoObj, ${detail.javaFlieName}CVal.FUNC_ID,
        tableId);

        impHelper.setstrMSGLTM(strMSGLTM);// 设置消息批次
        impHelper.setCurrentSheetNo(currentSheetNo);// 设置当前工作表编号
        impHelper.setRowNoOfFieldName(rowNoOfFieldName);// 设置字段名所在的行号
        impHelper.setRowNoOfBeginDataRow(rowNoOfBeginDataRow);// 设置开始数据行的行号
        impHelper.setRowNoOfEndDataRow(rowNoOfEndDataRow);// 设置结束数据行的行号
        impHelper.setisContinueToNextRow(isContinueToNextRow);// 设置当前行处理失败时是否继续处理下一行
        //impHelper.setCroDetailCheck(true);
        // 执行逻辑
        if (ImpFmFileCVal.EXPORT_TYPE_XLSX.equalsIgnoreCase(fileType)
        || ImpFmFileCVal.EXPORT_TYPE_XLS.equalsIgnoreCase(fileType)) {
        // Excel文件
        result = ImportFromExcelUtil.importData(impHelper);// 导入数据

        } else if (ImpFmFileCVal.EXPORT_TYPE_CSV.equalsIgnoreCase(fileType)) {
        // CSV文件
        result = ImportFromCsvUtil.importData(impHelper);// 导入数据
        }
        if (result == null) {
        result = new DefaultJsonResult();
        // 存放错误信息map
        Map<String, String> errorMap = new HashMap<String, String>();
        String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
        // 错误编号值
        // 待完善
        errorMap.put("msg", msg);
        result.setExtra(JSON.toJSONString(errorMap));
        result.setOK(false);
        result.setState(false);
        }
        } catch (Exception ex) {
        // 存放错误信息map
        Map<String, String> errorMap = new HashMap<String, String>();
        ex.printStackTrace();
        String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
        // 错误编号值
        // 待完善
        result.setErrMsg(msg);
        errorMap.put("msg", msg);
        result.setExtra(JSON.toJSONString(errorMap));
        result.setOK(false);
        result.setState(false);
        }
        // ============================================================================
        // ============================================================================
        // ============================================================================
        return result;
    }
    

}
